package initialition

import (
	"context"
	"encoding/json"
	"fmt"
	"github.com/go-redis/redis/v8"
	"github.com/nacos-group/nacos-sdk-go/clients"
	"github.com/nacos-group/nacos-sdk-go/common/constant"
	"github.com/nacos-group/nacos-sdk-go/vo"
	"github.com/spf13/viper"
	"go.uber.org/zap"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"os"
	"user_srv/global"
	"user_srv/internal/model/dao"
)

func init() {
	Zap()
	ReadConfig()
	Nacos()
	Mysql()
	Redis()
}

func Zap() {
	os.MkdirAll("./log", 0777)
	config := zap.NewDevelopmentConfig()
	config.OutputPaths = []string{
		"./log/dev.log",
	}
	build, err := config.Build()
	if err != nil {
		return
	}
	zap.ReplaceGlobals(build)
}

func ReadConfig() {
	viper.SetConfigFile("./config/config.dev.yaml")
	err := viper.ReadInConfig()
	if err != nil {
		panic(err)
	}
	viper.Unmarshal(&global.Config)
	fmt.Println(global.Config)
}
func Nacos() {
	//create clientConfig
	os.MkdirAll("./tmp/nacos/log", 0777)
	os.MkdirAll("./tmp/nacos/cache", 0777)
	clientConfig := constant.ClientConfig{
		NamespaceId:         global.Config.Nacos.NameSpace, //we can create multiple clients with different namespaceId to support multiple namespace.When namespace is public, fill in the blank string here.
		TimeoutMs:           5000,
		NotLoadCacheAtStart: true,
		LogDir:              "./tmp/nacos/log",
		CacheDir:            "./tmp/nacos/cache",
		LogLevel:            "debug",
		Username:            global.Config.Nacos.UserName,
		Password:            global.Config.Nacos.Password,
	}
	// At least one ServerConfig
	serverConfigs := []constant.ServerConfig{
		{
			IpAddr:      global.Config.Nacos.Addr,
			ContextPath: "/nacos",
			Port:        global.Config.Nacos.Port,
			Scheme:      "http",
		},
	}
	// Another way of create config client for dynamic configuration (recommend)
	configClient, err := clients.NewConfigClient(
		vo.NacosClientParam{
			ClientConfig:  &clientConfig,
			ServerConfigs: serverConfigs,
		},
	)
	if err != nil {
		panic(err)
	}
	content, err := configClient.GetConfig(vo.ConfigParam{
		DataId: global.Config.Nacos.DataId,
		Group:  global.Config.Nacos.Group,
	})
	//fmt.Println(content)
	err = json.Unmarshal([]byte(content), &global.T)
	if err != nil {
		panic(err)
	}

}
func Mysql() {
	var err error
	config := global.T.Mysql
	dsn := fmt.Sprintf("%s:%s@(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local", config.User, config.Password, config.Host, config.Port, config.Database)
	global.DB, err = gorm.Open(mysql.Open(dsn))
	if err != nil {
		panic(err)
	}
	fmt.Println("mysql")
	global.DB.AutoMigrate(&dao.Coupon{}, &dao.Study{}, &dao.Orders{}, &dao.Pay{})
}
func Redis() {
	config := global.T.Redis
	global.Rdb = redis.NewClient(&redis.Options{
		Addr:     config.Host,
		Password: config.Password,
		DB:       2,
	})
	err := global.Rdb.Ping(context.Background()).Err()
	if err != nil {
		panic(err)
	}
	fmt.Println("redis")
}
